//
// Created by wangxn on 2016/4/18.
//


#include "../../lib/comprass/compress.h"
#include <stdio.h>
#include <stdlib.h>
#include "../test.h"
#include <string.h>

/**
 * 压缩一个文本文件,然后将压缩之后的内容保存为另外一个文件
 */
void lz77_compress_test(){
    FILE *file = NULL;
    file = fopen("D:/c_note.txt", "rb");
    if (file == NULL) {
        printf("open file err\n");
        return;
    }

    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    fseek(file, 0, SEEK_SET);

    printf("file 'size : %ld\n", size);
    const unsigned char *buf = (unsigned char *)malloc(size * sizeof(unsigned char));
    fread((void *)buf, size, sizeof(unsigned char), file);

    unsigned char *compressed;
    int compressed_size = 0;
    if((compressed_size = lz77_compress(buf, &compressed, size)) <= 0) {
        printf("%s\n", "compress fail");
        return;
    }

    printf("compressed content size : %d\n", compressed_size);

    FILE *file2 = NULL;
    file2 = fopen("D:/c_note.lz77", "wb");
    if (file2 == NULL) {
        printf("%s\n", "write file open err");
        return;
    }

    fwrite((const void *)(compressed), compressed_size, sizeof(unsigned char), file2);
    printf("%s\n", "write file end");

    fclose(file2);
    fclose(file);

    return;
}

/**
 * 将压缩数据之后的文件还原成压缩之前的文件
 */
void lz77_uncompress_test(){

    FILE *file = NULL;
    file = fopen("D:/c_note.lz77", "rb");
    if (file == NULL) {
        printf("open file err\n");
        return;
    }

    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    fseek(file, 0, SEEK_SET);

    unsigned char *buf = (unsigned char *)malloc(size * sizeof(unsigned char));
    memset(buf, 0, size * sizeof(unsigned char));

    fread((void *)buf, size, sizeof(unsigned char), file);
    fclose(file);

    printf("%s\n", "read to buf end");

    unsigned char * original;
    if((size = lz77_uncompress(buf, &original)) <= 0) {
        printf("%s\n", "uncompress fail");
        return;
    }

//    printf("%s\n", *original);

    FILE *file2 = NULL;
    file2 = fopen("D:/c_note2.txt", "wb");
    if (file2 == NULL) {
        printf("%s\n", "write file open err");
        return;
    }

    fwrite((const void *)(original), size, sizeof(unsigned char), file2);
    printf("%s\n", "write file end");

    fclose(file2);
    return;
}
